package org.jeecg.modules.basic.guest.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.basic.entry.util.SenseTimeEnumToPrivate;
import org.jeecg.modules.basic.guest.entity.LwgyInoutGuest;
import org.jeecg.modules.basic.guest.service.ILwgyInoutGuestService;
import org.jeecg.modules.basic.readidcard.entity.LwgyInoutIdcard;
import org.jeecg.modules.basic.readidcard.service.ILwgyInoutIdcardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* @Description: 外来人员管理
* @Author: jeecg-boot
* @Date:   2021-03-17
* @Version: V1.0
*/
@Api(tags="外来人员管理")
@RestController
@RequestMapping("/guest/lwgyInoutGuest")
@Slf4j
public class LwgyInoutGuestController extends JeecgController<LwgyInoutGuest, ILwgyInoutGuestService> {
   @Autowired
   private ILwgyInoutGuestService lwgyInoutGuestService;
    @Autowired
    private ILwgyInoutIdcardService iLwgyInoutIdcardService;


    /**
     * 分页列表查询
     *
     * @param lwgyInoutGuest
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "外来人员管理-分页列表查询")
    @ApiOperation(value="外来人员管理-分页列表查询", notes="外来人员管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(LwgyInoutGuest lwgyInoutGuest,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<LwgyInoutGuest> queryWrapper = QueryGenerator.initQueryWrapper(lwgyInoutGuest, req.getParameterMap());
        Page<LwgyInoutGuest> page = new Page<LwgyInoutGuest>(pageNo, pageSize);
        IPage<LwgyInoutGuest> pageList = lwgyInoutGuestService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

   /**
    *   添加
    *
    * @param lwgyInoutGuest
    * @return
    */
   @AutoLog(value = "外来人员管理-添加")
   @ApiOperation(value="外来人员管理-添加", notes="外来人员管理-添加")
   @PostMapping(value = "/add")
   public Result<?> add(@RequestBody LwgyInoutGuest lwgyInoutGuest) throws Exception {
       lwgyInoutGuestService.save(lwgyInoutGuest);
       return Result.OK("添加成功！");
   }

   /**
    *  编辑
    *
    * @param lwgyInoutGuest
    * @return
    */
   @AutoLog(value = "外来人员管理-编辑")
   @ApiOperation(value="外来人员管理-编辑", notes="外来人员管理-编辑")
   @PutMapping(value = "/edit")
   public Result<?> edit(@RequestBody LwgyInoutGuest lwgyInoutGuest) {
       lwgyInoutGuestService.updateById(lwgyInoutGuest);
       return Result.OK("编辑成功!");
   }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "外来人员管理-通过id删除")
   @ApiOperation(value="外来人员管理-通过id删除", notes="外来人员管理-通过id删除")
   @DeleteMapping(value = "/delete")
   public Result<?> delete(@RequestParam(name="id",required=true) String id) {
       lwgyInoutGuestService.removeById(id);
       return Result.OK("删除成功!");
   }
   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "外来人员管理-批量删除")
   @ApiOperation(value="外来人员管理-批量删除", notes="外来人员管理-批量删除")
   @DeleteMapping(value = "/deleteBatch")
   public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.lwgyInoutGuestService.removeByIds(Arrays.asList(ids.split(",")));
       return Result.OK("批量删除成功!");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   @AutoLog(value = "外来人员管理-通过id查询")
   @ApiOperation(value="外来人员管理-通过id查询", notes="外来人员管理-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
       LwgyInoutGuest lwgyInoutGuest = lwgyInoutGuestService.getById(id);
       if(lwgyInoutGuest==null) {
           return Result.error("未找到对应数据");
       }
       return Result.OK(lwgyInoutGuest);
   }

   /**
   * 导出excel
   *
   * @param request
   * @param lwgyInoutGuest
   */
   @RequestMapping(value = "/exportXls")
   public ModelAndView exportXls(HttpServletRequest request, LwgyInoutGuest lwgyInoutGuest) {
       return super.exportXls(request, lwgyInoutGuest, LwgyInoutGuest.class, "外来人员管理");
   }

   /**
     * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       return super.importExcel(request, response, LwgyInoutGuest.class);
   }


    /**
     *   审批
     *
     * @param lwgyInoutGuest
     * @return
     */
    @AutoLog(value = "外来人员管理-审批(公有云)")
    @ApiOperation(value="外来人员管理-审批(公有云)", notes="外来人员管理-审批(公有云)")
    @PostMapping(value = "/approveGuestToPublic")
    public Result<?> approveGuestToPublic(@RequestBody LwgyInoutGuest lwgyInoutGuest) throws Exception {
        if(lwgyInoutGuest.getState().equals("1")){
            return Result.error("该访客已审批，无需再次审批");
        }
        //查询是否存在访客信息，存在，修改，不存在，编辑。
        String user = lwgyInoutGuestService.queryUser(2,lwgyInoutGuest.getGuestName(),lwgyInoutGuest.getGuestMobile(),lwgyInoutGuest.getGuestIdcard());
        System.out.println("访客用户是否存在："+user);
        JSONObject json = JSONObject.fromObject(user);
        String code = json.getString("code");
        System.out.println("code:"+code);
        String gusetId="";
        if("200".equals(code)){
            System.out.println("data:"+json.get("data"));
            System.out.println("data:"+json.get("data").toString());
            if("[]".equals(json.get("data").toString())){
                System.out.println("data为空。:true");
                return Result.OK("0");
            }else{//data不为空。修改
                JSONObject data = json.getJSONObject("data");
                gusetId = data.getString("id");
                return Result.OK(gusetId);
            }

        }else{
            String messagezk =  SenseTimeEnumToPrivate.getError(code);
            return Result.error("查询失败，下发到通道机时："+messagezk);
        }
    }

    /**
     *   审批
     *
     * @param lwgyInoutGuest
     * @return
     */
    @AutoLog(value = "外来人员管理-审批(私有云)")
    @ApiOperation(value="外来人员管理-审批(私有云)", notes="外来人员管理-审批(私有云)")
    @PostMapping(value = "/approveGuestToPrivate")
    public Result<?> approveGuestToPrivate(@RequestBody LwgyInoutGuest lwgyInoutGuest) throws Exception {
        if(lwgyInoutGuest.getState().equals("1")){
            return Result.error("该访客已审批，无需再次审批");
        }
        //查询是否存在访客信息，存在，修改，不存在，编辑。
        String user = lwgyInoutGuestService.queryUser(2,lwgyInoutGuest.getGuestName(),lwgyInoutGuest.getGuestMobile(),lwgyInoutGuest.getGuestIdcard());
        System.out.println("访客用户是否存在："+user);
        JSONObject json = JSONObject.fromObject(user);
        String code = json.getString("code");
        System.out.println("code:"+code);
        String gusetId="";
        if("200".equals(code)){
            System.out.println("data:"+json.get("data"));
            System.out.println("data:"+json.get("data").toString());
            if("[]".equals(json.get("data").toString())){
                System.out.println("data为空。:true");
                return Result.OK("0");
            }else{//data不为空。修改
                JSONObject data = json.getJSONObject("data");
                gusetId = data.getString("id");
                return Result.OK(gusetId);
            }

        }else{
            String messagezk =  SenseTimeEnumToPrivate.getError(code);
            return Result.error("查询失败，下发到通道机时："+messagezk);
        }
    }
    /**
     *   获取访客二维码
     *
     * @return
     */
    @AutoLog(value = "获取访客二维码（公有云）")
    @ApiOperation(value="获取访客二维码（公有云）", notes="获取访客二维码（公有云）")
    @PostMapping(value = "/guestQrCodeToPublic")
    public Result<?> guestQrCodeToPublic(@RequestParam(name="userId",required=true) String userId) throws Exception {
        String groupString = lwgyInoutGuestService.queryQrcodeByIdToPublic(userId);
        return Result.OK(groupString);
    }

    /**
     *   获取访客二维码
     *
     * @return
     */
    @AutoLog(value = "获取访客二维码(私有云)")
    @ApiOperation(value="获取访客二维码(私有云)", notes="获取访客二维码(私有云)")
    @PostMapping(value = "/guestQrCodeToPrivate")
    public Result<?> guestQrCodeToPrivate(@RequestParam(name="userId",required=true) String userId) throws Exception {
        String groupString = lwgyInoutGuestService.queryQrcodeByIdToPrivate(userId);
        return Result.OK(groupString);
    }

    /**
     * 远程开关门---访客扫描身份证开关门
     * */
    @AutoLog(value = "远程开关门")
    @ApiOperation(value="远程开关门", notes="远程开关门")
    @PostMapping(value = "/deviceOpen")
    public Result<?> deviceOpen(@RequestBody Map<String, Object> msg){
        JSONObject json = JSONObject.fromObject(msg);
        System.out.println("json--:" + json);
        String name = json.getString("name");
        String sex = json.getString("sex");
        String nation = json.getString("nation");
        String birthday = json.getString("birthday");
        String idcard = json.getString("idcard");
        String profile = json.getString("profile");

        int sexInt=0;
        if(sex.equals("男")){
            sexInt=1;
        }else{
            sexInt=2;
        }

        System.out.println("身份证号:"+idcard+"姓名："+name+"性別："+sex);

        LwgyInoutIdcard lwgyInoutIdcard = new LwgyInoutIdcard();
        lwgyInoutIdcard.setName(name);
        lwgyInoutIdcard.setSex(sexInt+"");
        lwgyInoutIdcard.setNation(nation);
        lwgyInoutIdcard.setBirthday(birthday);
        lwgyInoutIdcard.setIdcard(idcard);
        lwgyInoutIdcard.setProfile(profile);
        Date date = new Date();// 获取当前时间
        lwgyInoutIdcard.setTime(date);
        //通过身份号比对访客中是否存在改用户
        Boolean b = lwgyInoutGuestService.checkGuest(idcard);
        if(true){
            lwgyInoutIdcard.setType("1");
            iLwgyInoutIdcardService.save(lwgyInoutIdcard);
        }else{
            lwgyInoutIdcard.setType("0");
            iLwgyInoutIdcardService.save(lwgyInoutIdcard);
        }


        try{
           lwgyInoutGuestService.deviceOpen();
       }catch (Exception e){
           e.printStackTrace();
           return Result.error("开关失败");
       }
        return Result.OK();
    }

    /**
     * 往商汤添加访客信息
     * */

    @PostMapping(value = "/addToSenseTimeToPublic")
    public Result<?> addToSenseTimeToPublic(@RequestBody LwgyInoutGuest lwgyInoutGuest) throws Exception {
        //添加商汤系统中
        String result = lwgyInoutGuestService.saveGuestToPublic(lwgyInoutGuest);
        JSONObject json = JSONObject.fromObject(result);
        String code = json.getString("code");
        String message = json.getString("message");
        JSONObject data = json.getJSONObject("data");
        if("200".equals(code)){
            data = json.getJSONObject("data");
            String id = data.getString("id");
            lwgyInoutGuest.setGuestId(id);
            lwgyInoutGuest.setState("1");
            lwgyInoutGuestService.updateById(lwgyInoutGuest);
            return Result.OK("审批成功！");
        }else{
            String messagezk =  SenseTimeEnumToPrivate.getError(code);
            return Result.error("审批失败，下发到通道机时："+messagezk);
        }
    }

    /**
     * 往商汤添加访客信息
     * */

    @PostMapping(value = "/addToSenseTimeToPrivate")
    public Result<?> addToSenseTimeToPrivate(@RequestBody LwgyInoutGuest lwgyInoutGuest) throws Exception {
        //添加商汤系统中
        String result = lwgyInoutGuestService.saveGuestToPrivate(lwgyInoutGuest);
        JSONObject json = JSONObject.fromObject(result);
        String code = json.getString("code");
        String message = json.getString("message");
        JSONObject data = json.getJSONObject("data");
        if("200".equals(code)){
            data = json.getJSONObject("data");
            String id = data.getString("id");
            lwgyInoutGuest.setGuestId(id);
            lwgyInoutGuest.setState("1");
            lwgyInoutGuestService.updateById(lwgyInoutGuest);
            return Result.OK("审批成功！");
        }else{
            String messagezk =  SenseTimeEnumToPrivate.getError(code);
            return Result.error("审批失败，下发到通道机时："+messagezk);
        }
    }
    //查询访客列表
    @GetMapping(value = "/getGuest")
    public Result<?> getGuest(String mobile) {

        List<LwgyInoutGuest> list = lwgyInoutGuestService.getGuest(mobile);

        return Result.OK(list);
    }
}

